#include "daemon_sub_process.h"

SubProcess_t *deamon_sub_process_init(char *cmd_param)
{
    // 申请内存
    SubProcess_t *sub_process = (SubProcess_t *)malloc(sizeof(SubProcess_t));

    // 初始化sp属性
    sub_process->cmd_param = cmd_param;
    sub_process->pid = -1;
    sub_process->fail_count = 0;

    return sub_process;
}

int deamon_sub_process_checkStart(SubProcess_t *sub_process)
{
    int status;
    // 检测子进程是否正在运行中，如果是直接返回
    // waitpiad不会真等子进程结束，如果子进程正在运行，返回0 如果进程结束了，会奖进程结束时的状态保存到status中
    if (sub_process->pid > 0 && waitpid(sub_process->pid, &status, WNOHANG) == 0)
    {
        log_debug("进程 %s 正在运行中", sub_process->cmd_param);
        return 0;
    }
    // 如果子进程是失败结束，记录失败次数，如果失败次数超过指定值次，则重启子进程
    if (status == -1)
    {
        sub_process->fail_count++;
        if (sub_process->fail_count > MAX_FAIL_COUNT)
        {
            reboot(RB_AUTOBOOT);
        }
    }
    // 创建子进程 ，在子进程中执行程序
    sub_process->pid = fork();
    if (sub_process->pid == 0)
    {
        char *argv = {EXE_PATH, sub_process->cmd_param, NULL};
        execve(EXE_PATH, argv, NULL);
        log_error("execve error %s", sub_process->cmd_param);

        _exit(EXIT_FAILURE);
    }
    return 0;
}

void deamon_sub_process_close(SubProcess_t *sub_process)
{
    // kill 子进程
    kill(sub_process->pid, SIGTERM);
    // 等待子进程结束
    waitpid(sub_process->pid, NULL, 0);

    free(sub_process);
}
